import math
import time

from selenium.common import NoSuchElementException
from selenium.webdriver import ActionChains, Keys
from selenium.webdriver.common.by import By

from libs.action import WebDriverAction
from libs.game import Game
from libs.image import ImageTool
from libs.log import Log
from libs.movement import Movement
from libs.task_helper import TaskHelper
from libs.trade_helper import TradeHelper
from libs.window import AdsWindow


def get_chest_name(item_name):
    return str(item_name).lower().replace(' ', '_')


if __name__ == "__main__":
    parser = TaskHelper.default_args_parser('Wine')
    args = parser.parse_args()
    task_helper = TaskHelper.from_args(args)

    try:
        user_id = args.user_id
        log = Log(user_id)
        driver = AdsWindow(user_id).open(False)
        game = Game(driver, user_id)
        action = WebDriverAction(driver)
        movement = Movement(driver)
        image_tool = ImageTool(driver)
        trade_helper = TradeHelper(driver, user_id)
        ac = ActionChains(driver)
        collect_items = ['Silk Fiber']

        land_map = {
            "101": 3450,
            "105": 1702
        }
        land_no = land_map.get(str(user_id))

        game.enter_game()
        storage_loc = None
        for _ in range(3):
            storage_loc = image_tool.find_target('storage.png')
            if storage_loc is not None:
                break
            log.debug(f'goto_land {land_no}')
            action.goto_spec()
            action.goto_land(land_no)
            if int(user_id) == 101:
                movement.keep_move_up(1.6)
                movement.keep_move_left(3)
            else:
                movement.keep_move_up(1.2)
                movement.keep_move_right(3)
            time.sleep(5)
            continue
        time.sleep(1)
        game.chest_out(*storage_loc, collect_items, 999)

        action.escape()
        action.goto_spec()
        shd_image = 'spec_house_door.png'
        for _ in range(3):
            shd_loc = image_tool.find_target(shd_image)
            if shd_loc is None:
                movement.keep_move_up(2)
            else:
                break
        action.move_to_target(shd_image)
        action.wait_page_loaded()
        movement.keep_move_left(2.5)
        movement.keep_move_left(2.5)
        movement.keep_move_down(0.5)

        for collect_name in collect_items:
            chest_name = get_chest_name(collect_name)
            chest_locs = image_tool.find_all_targets('chest_v3.png', (200, 600, 750, 800))
            for _ in range(2):
                target_loc = None
                is_empty_chest = False
                for chest_loc in chest_locs:
                    action.move_by_offset(*chest_loc)
                    hover_bubble = action.hover_bubble(*chest_loc)
                    if hover_bubble is None:
                        is_empty_chest = True
                        target_loc = chest_loc
                        break
                    if hover_bubble == chest_name:
                        target_loc = chest_loc
                        break

                if target_loc is None:
                    Log('notify').info(f'[{user_id}]: no-available-chest')
                else:
                    time.sleep(1)
                    game.open_backpack()
                    action.click_by_offset(*target_loc)
                    if is_empty_chest:
                        chest_name_input = action.find_element(By.CLASS_NAME, 'InventoryWindow_inventoryNameInput__R6cxL',
                                                               'ChestNameInput', 1)
                        if chest_name_input is not None:
                            chest_name_input.send_keys(chest_name)

                    cell_items = driver.find_elements(By.CLASS_NAME, 'Hud_item__YGtIC')
                    for index, cell_elem in enumerate(cell_items):
                        try:
                            qty_elem = cell_elem.find_element(By.CLASS_NAME, 'Hud_quantity__V_YWQ')
                            if qty_elem.text == '':
                                qty = 1
                            else:
                                qty = int(qty_elem.text.replace('x', ''))
                        except NoSuchElementException:
                            continue
                        if qty < 999:
                            continue
                        ac.move_to_element(cell_elem).perform()
                        try:
                            hover_title_elem = driver.find_element(By.XPATH,
                                                                   "//span[@class='ItemStyles_tooltipTitle____kIs']")
                            item_name = hover_title_elem.text
                            if item_name == collect_name:
                                ac.context_click().perform()
                                time.sleep(1)
                        except NoSuchElementException:
                            continue

                    game.open_backpack()
                    empty_cell = 0
                    cell_items = driver.find_elements(By.CLASS_NAME, 'InventoryWindow_inventoryItem__z7YhV')
                    for index, cell_elem in enumerate(cell_items):
                        try:
                            qty_elem = cell_elem.find_element(By.CLASS_NAME, 'InventoryWindow_itemQuantity__SNjQU')
                            if qty_elem.text == '':
                                qty = 1
                            else:
                                qty = int(qty_elem.text.replace('x', ''))
                        except NoSuchElementException:
                            empty_cell += 1

                    if empty_cell == 0:
                        chest_name_input = action.find_element(By.CLASS_NAME, 'InventoryWindow_inventoryNameInput__R6cxL',
                                                               'ChestNameInput', 1)
                        if chest_name_input is not None:
                            chest_name_input.send_keys(Keys.CONTROL, "a")
                            chest_name_input.send_keys(chest_name + "_full")

                    action.escape()
                    action.escape()
                    game.close_backpack()
                    if empty_cell == 0:
                        continue
                    else:
                        break

            task_helper.task_success()
            task_helper.add_task('collect.py', 60 * 60 * 4, False, False)
    except Exception as e:
        task_helper.add_task('collect.py', 60 * 60 * 4, False, True)
        raise e
